package org.overtheair.say.logic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;


/**
 * Execute the call to a Dolcevita webservice and return the result
 * 
 * 
 * @author Alfredo Morresi
 * 
 */
public class WebserviceRequestClient
{
	protected static final String PROP_QUERYOBJECT = "jsonInput";
	protected static final String PROP_APIKEY = "apikey";

	// ************************************************************************
	// ctor
	// ************************************************************************

	public WebserviceRequestClient() {
	}



	// ************************************************************************
	// Public methods and properties
	// ************************************************************************

	/**
	 * Call the dolcevita webservice via a GET request
	 * 
	 * @param url
	 *            the Url of the webservice
	 * @param queryObject
	 *            the query object with the request to execute
	 * @param apiKey
	 *            the api key for dolcevita services
	 * @return the string returned from the webservice
	 */
	public String RequestGET(String url)
	{
		// reference here:
		// http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/

		HttpGet httpGet;
		String result;
		StringBuilder newUrl;

		result = "";

		newUrl = new StringBuilder();
		newUrl.append(url);
//		newUrl.append("?");
//		newUrl.append(PROP_QUERYOBJECT);
//		newUrl.append("=");
//		newUrl.append(convertQueryToString(queryObject));
//		newUrl.append("&");
//		newUrl.append(PROP_APIKEY);
//		newUrl.append("=");
//		newUrl.append(apiKey);

		// prepare a request object
		httpGet = new HttpGet(newUrl.toString().replace(" ", "%20"));

		// Get hold of the response entity

		result = executeResponse(httpGet);

		return result;
	}

	/**
	 * Call the dolcevita webservice via a POST request
	 * 
	 * @param baseUrl
	 *            the base URL of the webservice
	 * @return the string returned from the webservice
	 */
	public String RequestPOST(String baseUrl)
	{
		// reference here:
		// http://www.androidsnippets.org/snippets/36/
		// another reference, but with different method, here
		// http://www.anddev.org/doing_http_post_with_android-t492.html

		HttpPost httpPost;
		String result;

		// create the client
		httpPost = new HttpPost(baseUrl);

		//TODO
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//		nameValuePairs.add(new BasicNameValuePair(PROP_QUERYOBJECT,
//				convertQueryToString(queryObject)));
//		nameValuePairs.add(new BasicNameValuePair(PROP_APIKEY, apiKey));

		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			result = executeResponse(httpPost);

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			result = "";
		}

		return result;
	}




	// ************************************************************************
	// Private methods and properties
	// ************************************************************************

	protected String executeResponse(HttpUriRequest httpRequest) {
		HttpClient httpClient;
		HttpResponse response;
		String result;

		// create the client
		httpClient = new DefaultHttpClient();

		result = "";
		try {
			response = httpClient.execute(httpRequest);
			// Log.i("Dolcevita",response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {
				InputStream instream = entity.getContent();
				result = convertStreamToString(instream);
				// Log.i("Dolcevita",result);
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	protected static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}


}

/**
 * test reply:
 * 
 */
